//  getSvg.js
const fs = require('fs');
const path = require('path');
const cmder = require('child_process');

const svgDir = path.resolve(__dirname, '../src/assets/svg/');
const fontsDir = path.resolve(__dirname, '../src/assets/fonts/');
const fontsJsonDir = path.resolve(__dirname, '../src/component/');
const targetIosFontsDir = path.resolve(__dirname, '../ios/');
const targetAndroidFontsDir = path.resolve(__dirname, '../android/app/src/main/assets/fonts/');
let args = process.argv.splice(2);


if (args.length === 0) {
    const com = 'node iconfont.js';
    console.log(
        'you can use \n' +
        '-  "generate" to generate iconfont.json file \n' +
        '-  "copy" to copy font file to iOS/Android project directory \n' +
        '-  "directory to check required directory is exists'
    );
} else {
    const arg = args[0];
    if (arg === 'generate') {
        generateJsonFile();
    }
    if (arg === 'copy') {
        copyFonts();
    }
    if (arg === 'watch') {
        console.log('watching ' + fontsDir + ' ...');
        fs.watch(fontsDir, file => {
            copyFonts();
            cmder.exec('npm run ios');
        });
        console.log('watching ' + svgDir + ' ...');
        fs.watch(svgDir, file => {
            generateJsonFile();
            cmder.exec('npm run ios');
        });
    }
    if (arg === 'directory') {
        checkDirectory();
    }
}

function generateJsonFile() {
    function trans(data) {
        var obj = {};

        data.map((item) => {
            var ddd = item.split('=');
            ddd[1] = ddd[1].replace(/\"/g, '').replace(/&#/g, '');
            if (ddd[1] != 'x') {
                if (ddd[0] == 'unicode') {
                    var unicode = ddd[1];
                    obj[ddd[0]] = unicode.toString();
                } else {
                    obj[ddd[0]] = ddd[1];
                }
            }
        });
        return obj;
    }

    // 读取单个文件
    function readfile(filename) {
        return new Promise((resolve, reject) => {
            fs.readFile(path.join(svgDir, filename), 'utf8', function (err, data) {
                data.replace(/<\?xml.*?\?>|<\!--.*?-->|<!DOCTYPE.*?>/g, '');
                var origin = data.match(/<glyph glyph-name.*/g);
                var objArr = [];
                origin.map((item, index) => {
                    item = item.replace(/;/g, '');
                    var usData = item.match(/glyph-name=".*?"|unicode=".*?"/g);
                    var obj = trans(usData);
                    if (Object.keys(obj).length > 0) {
                        objArr.push(obj)
                    }
                });
                if (err) {
                    eject(err);
                }
                else {
                    resolve(objArr);
                }
            });
        });
    }

    // 读取SVG文件夹下所有svg
    function readSvgs() {
        return new Promise((resolve, reject) => {
            fs.readdir(svgDir, function (err, files) {
                if (err) reject(err);
                Promise.all(files.map(filename => readfile(filename)))
                    .then(data => resolve(data))
                    .catch(err => reject(err));
            });
        });
    }

    // 生成 iconfont.json
    readSvgs().then((data) => {
        let svgFile = '';

        svgFile += '{\n';

        data[0].map((item, index) => {

            if (index === data[0].length - 1) {
                svgFile = svgFile + '\t"' + 'icon-'+item['glyph-name'] + '":' + item['unicode'] + '\n';
            } else {
                svgFile = svgFile + '\t"' + 'icon-'+item['glyph-name'] + '":' + item['unicode'] + ',\n';
            }

        });
        svgFile += '}';
        // let svgFile = 'export default ' + JSON.stringify(Object.assign.apply(this, data));
        fs.writeFile(path.join(fontsJsonDir, './iconfont.json'), svgFile, function (err) {
            if (err) {
                throw new Error(err)
            }
            else {
                console.log(path.join(fontsJsonDir, './iconfont.json') + '生成成功');
            }
        })
    }).catch(err => {
        //console.log(err);
        throw new Error(err);
    });
}

function copyFonts() {

    //拷贝到对应项目
    function copy(src, dst) {
        fs.createReadStream(src).pipe(fs.createWriteStream(dst));
    }

    // 读取fonts文件夹下所有svg
    function readFonts(tar) {
        return new Promise((resolve, reject) => {
            fs.readdir(fontsDir, function (err, files) {
                if (err) reject(err);
                let fonts = [];
                files.map(filename => {
                    if (filename === 'iconfont.ttf') {
                        copy(path.join(fontsDir, filename), path.join(tar, filename));
                        fonts.push(filename);
                    }
                });
                if (fonts.length > 0) {
                    resolve({message: '拷贝' + fonts.join(',') + '到:' + tar + '成功！！！'});
                } else {
                    resolve({message: '暂无iconfont.ttf字体文件更新'});
                }
            })
        })
    }

    readFonts(targetIosFontsDir).then(({message}) => {
        console.log(message);
    }).catch(err => {
        throw new Error(err);
    });

    readFonts(targetAndroidFontsDir).then(({message}) => {
        console.log(message);
    }).catch(err => {
        throw new Error(err);
    });
}

function checkDirectory() {
    fs.exists(svgDir, (exists) => {
        console.log(svgDir+' exists is '+exists);
        if(!exists){
            cmder.exec('mkdir '+ svgDir);
            console.log('the svg directory is not exists wo have created it');
        }
    })
}
